//
//  WBComposeView.swift
//  WB123
//
//  Created by xuyunde mac pro on 2017/7/8.
//  Copyright © 2017年 NSObjiect. All rights reserved.
//

import UIKit
import pop
class WBComposeView: UIView {
    
    // 记录父控件
    var target: UIViewController?
    // 保存自定义按钮
    lazy var composeButtonList:[WBComposeButton] = [WBComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 类方法显示
    class func show(target: UIViewController){
        let composeView = WBComposeView()
        // 赋值
        composeView.target = target
        target.view.addSubview(composeView)
        // 设置6个按钮的弹簧动画
        composeView.setupComposeButtonsAnim(isUp: true)
    }
    
    private func setupUI(){
        backgroundColor = randomColor()
        
        // 添加控件
        addSubview(bgImageView)
        
        // 添加约束
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        addComposeButtons()

    }
    
    //MARK: - 懒加载控件
    // 背景图片
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenSnap()!.applyLightEffect())

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setupComposeButtonsAnim(isUp: false)
        // 延迟删除当前界面
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.removeFromSuperview()
        }

    }
   
}

extension WBComposeView{
    // 设置弹簧动画
    fileprivate func setupComposeButtonsAnim(isUp: Bool){
        
        // 350
        var buttonMargin: CGFloat = -350
        
        // 消失动画
        if !isUp {
            buttonMargin = 350
            composeButtonList = composeButtonList.reversed()
        }
        
        for (i, composeButton) in composeButtonList.enumerated(){
        
        let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        anSpring?.toValue = CGPoint(x: composeButton.center.x, y: composeButton.center.y + buttonMargin)
        anSpring?.beginTime = CACurrentMediaTime() + Double(i)*0.025
        anSpring?.springBounciness = 10
        composeButton.pop_add(anSpring, forKey: nil)
        }
        
    }
}

extension WBComposeView{
    fileprivate func addComposeButtons(){
        // 获取plist里面模型数组
        
        let composeList = loadComposePlist()
        // 计算按钮的宽高
        let composeButtonW: CGFloat = 80
        let composeButtonH: CGFloat = 110
        // 间距
        let composeMargin = (SCREENW - composeButtonW * 3)/4
        // 循环6次
        for (i, composeModel) in composeList.enumerated(){
            // 计算行和列索引
            let row = CGFloat(i/3)
            let col = CGFloat(i%3)
            // 创建按钮
            let button = WBComposeButton()
            // 赋值
            button.composeModel = composeModel
            // 监听事件
            button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
            button.frame = CGRect(x: composeMargin + (composeButtonW+composeMargin)*col, y: SCREENH + (composeMargin+composeButtonH)*row, width: composeButtonW, height: composeButtonH)
            button.setImage(UIImage(named:composeModel.icon ?? ""), for: UIControlState.normal)
            button.setTitle(composeModel.title, for: UIControlState.normal)
            addSubview(button)
            // 添加
            composeButtonList.append(button)
        }
    }
}

extension WBComposeView{
    // 按钮事件
    @objc fileprivate func buttonClick(composeButton: WBComposeButton){
        // 设置动画
        UIView.animate(withDuration: 0.25, animations: {
            // 遍历按钮数组
            for button in self.composeButtonList{
                button.alpha = 0.2
                // 点击的按钮
                if button == composeButton{
                    // 放大
                    composeButton.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    // 缩小
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            
        }) { (_) in
            
            // 动画完成后 恢复原样
            UIView.animate(withDuration: 0.25, animations: {
                
                // 遍历按钮 恢复原状
                for button in self.composeButtonList{
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
                
            }, completion: { (_) in
                
                // 判断className是否为nil
                guard let className = composeButton.composeModel?.className else{
                    return
                }
                // 判断是否为nil 而且是否可以转成 UIViewController.Type
                guard let type = NSClassFromString(className) as? UIViewController.Type else{
                    return
                }
                // 通过anyclass 创建一个对象
                let vc = type.init()
                // 创建导航控制器
                let nav = WBNavigationController(rootViewController: vc)
                // 模态形式弹出
                self.target?.present(nav, animated: true, completion: {
                    // 移除
                    self.removeFromSuperview()
                })

            
            })

        }
    }
}

extension WBComposeView{
    //MARK: - 读取plist文件
    fileprivate func loadComposePlist() -> [HMComposeModel]{
        // 路径
        let file = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let plistArray = NSArray(contentsOfFile: file)!
        let tempList = NSArray.yy_modelArray(with: HMComposeModel.self, json: plistArray) as! [HMComposeModel]
        return tempList
    }
}
